<template>
  <div>
    <el-button type="primary" icon="el-icon-edit" plain style="margin-bottom: 20px" @click="hdlOpen(newForm)">
      {{ textMap['create'] }}
    </el-button>
    <el-card shadow="hover" :body-style="{ padding: '0px' }">

      <u-table
        :data="list"
        :page="false"
        :columns="columns"
        :options="{ headerCellStyle: { background:'#FAFAFA'}, stripe: true }"
      >
        <template v-slot:right>

          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button type="text" @click="hdlEdit(row)">编辑</el-button>
              <el-button type="text" @click="hdlDelete(row)">删除</el-button>
            </template>
          </el-table-column>

        </template>
      </u-table>

    </el-card>

    <u-dialog :title="textMap[dialogStatus]" :show.sync="dialogFormVisible" :append-to-body="true" @confirm="dialogStatus==='create'?hdlCreate():hdlUpdate()">
      <el-form ref="dialogForm" :rules="rules" :model="dataForm" label-width="100px">

        <el-form-item prop="type" label="月租类型">
          <el-radio-group v-model="dataForm.type">
            <el-radio :label="1">月租车</el-radio>
            <el-radio :label="2">半月租</el-radio>
            <el-radio :label="3">员工</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="name" label="月租标题">
          <el-input v-model="dataForm.name" placeholder="标题" clearable maxlength="6" show-word-limit />
        </el-form-item>

        <el-form-item prop="stock" label="库存数量">
          <el-input v-model="dataForm.stock" placeholder="库存数量" clearable maxlength="6" show-word-limit />
        </el-form-item>

        <el-form-item prop="area" label="停车区域">
          <el-input v-model="dataForm.area" placeholder="停车区域" clearable />
        </el-form-item>

        <el-form-item prop="car" label="科拓类型">
          <el-input v-model="dataForm.car" placeholder="科拓内部车编号" clearable maxlength="6" show-word-limit />
        </el-form-item>

        <el-form-item prop="value1" label="1个月">
          <el-input v-model="dataForm.value1" placeholder="价格" clearable maxlength="6" show-word-limit />
        </el-form-item>

        <el-form-item prop="value2" label="3个月">
          <el-input v-model="dataForm.value2" placeholder="价格" clearable maxlength="6" show-word-limit />
        </el-form-item>

        <el-form-item prop="value3" label="6个月">
          <el-input v-model="dataForm.value3" placeholder="价格" clearable maxlength="6" show-word-limit />
        </el-form-item>

        <el-form-item prop="value4" label="12个月">
          <el-input v-model="dataForm.value4" placeholder="价格" clearable maxlength="6" show-word-limit />
        </el-form-item>

        <el-form-item prop="note" label="月租备注">
          <u-tinymce v-model="dataForm.note" :height="300" />
        </el-form-item>

      </el-form>
    </u-dialog>

  </div>

</template>

<script>
/**
 * 业务组件 - 月租规则
 */
export default {
  name: 'Rental',
  props: {
    /** 数据源 */
    value: {
      type: [Array, String],
      default() {
        return []
      }
    }
  },
  data() {
    return {
      // 选择的会员
      columns: [
        {
          prop: 'type',
          label: '月租类型',
          formatter: (row) => {
            switch (row.type) {
              case 1:
                return '月租车';
              case 2:
                return '半月租';
              case 3:
                return '员工';
              default:
                return '';
            }
          }
        },
        {
          prop: 'name',
          label: '月租标题'
        },
        {
          prop: 'stock',
          label: '库存数量'
        },
        {
          prop: 'area',
          label: '停车区域'
        },
        {
          prop: 'car',
          label: '科拓类型'
        },
        {
          prop: 'value1',
          label: '1个月'
        },
        {
          prop: 'value2',
          label: '3个月'
        },
        {
          prop: 'value3',
          label: '6个月'
        },
        {
          prop: 'value4',
          label: '12个月'
        },
      ],
      // 选中的等级
      list: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑规则',
        create: '新增规则'
      },
      dataForm: {
        value: ''
      },
      rules: {
        title: [
          { required: true, message: '月租名称必填', trigger: ['blur'] }
        ],
        name: [
          { required: true, message: '月租名称必填', trigger: ['blur'] }
        ],
        car: [
          { required: true, message: '科拓类型必填', trigger: ['blur'] }
        ],
        stock: [
          { required: true, message: '库存数量必填', trigger: ['blur'] }
        ],
        type: [
          { required: true, message: '月租类型必填', trigger: ['blur'] }
        ],
        value1: [
          { required: true, message: '月租价格必填', trigger: ['blur'] }
        ]
      },
      // 删除选中数据
      selectData: [],
      newForm: {
        type: 1
      }
    }
  },
  watch: {
    // 监听数据
    value: {
      immediate: true,
      handler(val) {
        // 初始化数据
        this.loadData(val)
      }
    }
  },
  methods: {
    /**
     * 提交更新数据事件
     */
    hdlUpdate() {
      const self = this
      // 效验数据格式
      self.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          // 添加数据
          const { type } = self.dataForm

          const titles = {
            1: '月租车',
            2: '半月租',
            3: '员工'
          };
          self.dataForm.title = titles[type] || '';
          const foundIndex = self.list.findIndex(item => item.type === type)
          if (foundIndex !== -1) {
            // 替换列表中指定索引的对象
            self.list[foundIndex] = { ...self.dataForm }
          }
          // 按 type 从小到大排序
          self.list.sort((a, b) => a.type - b.type);
          // 关闭弹窗状态
          self.dialogFormVisible = false
          // 通知数据更新
          self.change()
        }
      })
    },
    // 编辑事件
    hdlEdit(row) {
      const self = this
      // 初始化数据源
      self.dataForm = Object.assign({}, row)
      // 打开编辑状态
      self.dialogStatus = 'update'
      // 打开弹框状态
      self.dialogFormVisible = true
      // 清除表单验证状态
      self.$nextTick(() => {
        self.$refs['dialogForm'].clearValidate()
      })
    },

    // 初始化数据
    async loadData(val) {
      if (val) {
        if (typeof this.value === 'string') {
          try {
            this.list = JSON.parse(this.value)
          } catch (error) {
            console.error('Invalid JSON string:', this.value)
            this.list = []
          }
        }
      }
    },
    // 通知数据更新
    change() {
      const { list } = this
      this.$emit('input', JSON.stringify(list))
      this.$emit('change', JSON.stringify(list))
    },
    /**
     * 打开新增窗口事件
     * @param row
     */
    hdlOpen(row) {
      const self = this
      // 初始化数据源
      self.dataForm = Object.assign({}, row)
      // 打开新增状态
      self.dialogStatus = 'create'
      // 打开弹框状态
      self.dialogFormVisible = true
      // 清除表单验证状态
      self.$nextTick(() => {
        self.$refs['dialogForm'].clearValidate()
      })
    },
    /**
     * 提交创建数据事件
     */
    hdlCreate() {
      const self = this
      // 效验数据格式
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          const { type } = self.dataForm

          // 检查 type 是否已存在
          const isExist = self.list.some(item => item.type === type);
          if (isExist) {
            this.$u.toast('该类型已存在，请勿重复添加！', 'error')
            return;
          }

          const titles = {
            1: '月租车',
            2: '半月租',
            3: '员工'
          };

          self.dataForm.title = titles[type] || '';
          // 添加数据
          self.list.push(self.dataForm)
          // 按 type 从小到大排序
          self.list.sort((a, b) => a.type - b.type);
          // 关闭弹窗状态
          self.dialogFormVisible = false
          // 通知数据更新
          self.change()
        }
      })
    },
    /**
     * 删除单个事件
     * @param row
     */
    hdlDelete(row) {
      const self = this
      // 模态对话框组件
      self.$confirm('确认删除该月租规则吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        // 处理确认事件
        self.list.splice(self.list.findIndex(item => item.type === row.type), 1)
        // 通知数据更新
        self.change()
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep{
  .el-input{
    width: 100% !important;
  }
}
</style>
